<template>
  <div>
  <a-card title="主机指标" :bordered="true" style="width: 100%" class="metric-vms">
    <div class="metric-vms-content">
      <div ref="cpuChart" :style="{ width: '50%', height: '300px' }"></div>
      <div ref="memChart" :style="{ width: '50%', height: '300px' }"></div>
    </div>
  </a-card>
  <a-card title="CPU详细使用率" :bordered="true" style="width: 100%" class="core-usage-vms">
    <div class="core-usage-vms-content">
      <CoreUsage v-for="(hostData, index) in coreUsageData" :host-data="hostData" :key="index"></CoreUsage>
    </div>
  </a-card>
  </div>
</template>

<script setup>
import CoreUsage from '@/components/CoreUsage.vue'

import * as echarts from 'echarts';
import { ref, onMounted, watch, nextTick, toRefs } from 'vue';
import { defineProps } from 'vue';

const props = defineProps({
  lastData: {
    type: Array,
    required: true
  }
});

const { lastData } = toRefs(props);
const groupData = ref({});
const coreUsageData = ref([]);
const cpuChart = ref(null);
const memChart = ref(null);
let cpuChartInstance = null;
let memChartInstance = null;
const coreChartInstances = ref({});

const initCharts = () => {
  cpuChartInstance = echarts.init(cpuChart.value);
  memChartInstance = echarts.init(memChart.value);
  updateCharts();
};

const initCoreUsageCharts = () => {
  coreUsageData.value.forEach(hostData => {
    const chartRef = coreChartInstances.value[hostData.Host];
    if (chartRef) {
      const chartInstance = echarts.init(chartRef);
      const option = {
        title: {
          text: hostData.Host,
          textStyle: {
            fontSize: 18,
            fontWeight: 500
          }
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: hostData.core_usages.map((_, index) => `Core ${index}`)
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} %'
          }
        },
        series: [
          {
            name: 'CPU使用',
            type: 'bar',
            data: hostData.core_usages.map(value => ({ value: parseFloat(value), itemStyle: { color: '#5470C6' } })),
            label: {
              show: true,
              position: 'top',  // 标签位置
              formatter: '{c} %',  // 显示数值及百分号
              fontSize: 12,        // 字体大小
              fontWeight: 'bold'   // 字体加粗
            }
          }
        ]
      };
      chartInstance.setOption(option);
    }
  });
};

const updateCharts = () => {
  const cpuData = groupData.value.total_cpu_usage || [];
  const memData = groupData.value.mem_used_percent || [];

  const cpuHosts = cpuData.map(item => item.Host);
  const cpuValues = cpuData.map(item => parseFloat(item.Value));

  const memHosts = memData.map(item => item.Host);
  const memValues = memData.map(item => parseFloat(item.Value));

  const cpuOption = {
    title: {
      text: 'CPU整体使用率',
      textStyle: {
        fontSize: 18,
        fontWeight: 500
      }
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: cpuHosts
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} %'
      }
    },
    series: [
      {
        name: 'CPU使用',
        type: 'bar',
        data: cpuValues.map(value => ({ value, itemStyle: { color: '#5470C6' } })),
        label: {
          show: true,
          position: 'top',  // 标签位置
          formatter: '{c} %',  // 显示数值及百分号
          fontSize: 12,        // 字体大小
          fontWeight: 'bold'   // 字体加粗
        }
      }
    ]
  };

  const memOption = {
    title: {
      text: '内存整体使用率',
      textStyle: {
        fontSize: 18,
        fontWeight: 500
      }
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: memHosts
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} %'
      }
    },
    series: [
      {
        name: '内存使用',
        type: 'bar',
        data: memValues.map(value => ({ value, itemStyle: { color: '#91CC75' } })),
        label: {
          show: true,
          position: 'top',  // 标签位置
          formatter: '{c} %',  // 显示数值及百分号
          fontSize: 12,        // 字体大小
          fontWeight: 'bold'   // 字体加粗
        }
      }
    ]
  };

  cpuChartInstance.setOption(cpuOption);
  memChartInstance.setOption(memOption);
  initCoreUsageCharts();
};

function groupByMetric(data) {
  let groupedResult = {
    total_cpu_usage: [],
    mem_used_percent: []
  };
  data.forEach(item => {
    groupedResult.total_cpu_usage.push({
      Host: item.Host,
      Value: item.total_cpu_usage
    });
    groupedResult.mem_used_percent.push({
      Host: item.Host,
      Value: item.mem_used_percent
    });
  });
  return groupedResult;
}

onMounted(() => {
  nextTick(() => {
    initCharts();
  });
});

watch(() => lastData.value, (newVal) => {
  let newArray = newVal.map(item => {
    return { ...item };
  });
  groupData.value = groupByMetric(newArray);
  coreUsageData.value = newArray.map(item => ({
    Host: item.Host,
    core_usages: item.core_usages
  }));
  console.log('New vmMetric value of lastData:', groupData.value);
  console.log('Core usage data:', coreUsageData.value);

  if (cpuChartInstance && memChartInstance) {
    updateCharts();
  }
});
</script>

<style lang="less">
.metric-vms {
  .ant-card-head-title {
    font-size: 1rem;
    font-weight: 600 !important;
  }
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  .metric-vms-content {
    display: flex;
    flex-direction: row;

    > div {
      flex: 1;
    }
  }

  .echarts-title {
    font-size: 1rem;
    font-weight: 500;
  }
}

.core-usage-vms {
  .ant-card-head-title {
    font-size: 1rem;
    font-weight: 600 !important;
  }
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  .core-usage-vms-content {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start; 

    > div {
      flex: 0 0 25%; 
      max-width: 25%; 
      box-sizing: border-box;
    }
  }
}
</style>
